<template>
  <div class="videowrapper container">
    <video class="h5video" :id="'video'+videoIndex" autoplay webkit-playsinline playsinline></video>
    <div class="h5controls">
      <div class="topShade">
        <!-- <div class="title">监控中心-大厅</div>-->
        <div class="cloud" @click="changeControls1">{{controlName}}</div>
      </div>
      <div class="bottomShade">
        <ul class="playControls" v-if="playControls">
          <li @click="videoClose1(videoId, $event)"><i class="iconfont icon_guanbi"></i></li>
          <li @click="videoSnapShot"><i class="iconfont icon_jietu"></i></li>
          <li @click="recordControl1" :style="recordStyle">
            <i class="iconfont" :class="recordIcon"></i>
          </li>
          <li @click="FullScreen1">
            <i :class="screenIcon"></i>
          </li>
          <li id="timeCount" v-if="timeCount">
            <span>{{h}}:{{m}}:{{s}}</span>
          </li>
        </ul>
        <ul class="brightControls" v-if="playControls">
          <li @click="changeStream1">
            <i :class="streamIcon"></i>
            <!--            <span class="changeName">码流切换</span>-->
            <!--            <span class="stream">主码流</span>-->
          </li>
          <li @click="changeProto1">
            <i :class="protoIcon"></i>
            <!--            <span class="changeName">协议切换</span>-->
            <!--            <span class="stream">RTC</span>-->
          </li>
        </ul>
        <ul class="directControls" v-if="cloudControls">
            <li class="up">
              <i class="iconfont icon_fangxiangjian" @mousedown="videoOperation1('up', $event)" @mouseup="videoOperation1('stop', $event)"   @touchstart ="videoOperation1('up', $event)" @touchend="videoOperation1('stop', $event)"></i>
            </li>
            <li class="right">
              <i class="iconfont icon_fangxiangjian" @mousedown="videoOperation1('right', $event)" @mouseup="videoOperation1('stop', $event)" @touchstart ="videoOperation1('right', $event)" @touchend="videoOperation1('stop', $event)"></i>
            </li>
            <li class="down">
              <i class="iconfont icon_fangxiangjian" @mousedown="videoOperation1('down', $event)" @mouseup="videoOperation1('stop', $event)" @touchstart ="videoOperation1('down', $event)" @touchend="videoOperation1('stop', $event)"></i>
            </li>
            <li class="left">
              <i class="iconfont icon_fangxiangjian" @mousedown="videoOperation1('left', $event)" @mouseup="videoOperation1('stop', $event)" @touchstart ="videoOperation1('left', $event)" @touchend="videoOperation1('stop', $event)"></i>
            </li>
          </ul>
        <ul class="zoomControls" v-if="cloudControls">
          <li class="zoomin">
            <i class="iconfont icon_gongnengjian_fangda" @mousedown="videoOperation1('zoomin', $event)" @mouseup="videoOperation1('stop', $event)"   @touchstart ="videoOperation1('zoomin', $event)" @touchend="videoOperation1('stop', $event)"></i>
          </li>
          <li class="zoomout">
            <i class="iconfont icon_gongnengjian_suoxiao" @mousedown="videoOperation1('zoomout', $event)" @mouseup="videoOperation1('stop', $event)"   @touchstart ="videoOperation1('zoomout', $event)" @touchend="videoOperation1('stop', $event)"></i>
          </li>
        </ul>
        <div class="positionControls" v-if="cloudControls">
          <span>预置位 {{presetNum}}/6</span>
          <ul class="dotList">
            <li @click="preset($event)">
              <span @dblclick="editName1($event)" class="valShow">{{preset1}}</span>
<!--              <span class="valShow">{{preset1}}</span>-->
              <i class="iconfont icon_jiasu1"></i>
              <div class="presetInput">
                <el-input :clearable="true" :autofocus="true"  v-model="preset1" placeholder="添加新预置点" @blur="confirm1"></el-input>
              </div>
              <i class="iconfont icon_shanchu" @click="deletePreset1($event, 'preset1')"></i>
            </li>
            <li @click="preset($event)">
              <span @dblclick="editName1($event)" class="valShow">{{preset2}}</span>
              <!--              <span class="valShow">{{preset1}}</span>-->
              <i class="iconfont icon_jiasu1"></i>
              <div class="presetInput">
                <el-input :clearable="true" :autofocus="true"   v-model="preset2" placeholder="添加新预置点" @blur="confirm1"></el-input>
              </div>
              <i class="iconfont icon_shanchu" @click="deletePreset1($event, 'preset2')"></i>
            </li>
            <li @click="preset($event)">
              <span @dblclick="editName1($event)" class="valShow">{{preset3}}</span>
              <!--              <span class="valShow">{{preset1}}</span>-->
              <i class="iconfont icon_jiasu1"></i>
              <div class="presetInput">
                <el-input :clearable="true" :autofocus="true"  v-model="preset3" placeholder="添加新预置点" @blur="confirm1"></el-input>
              </div>
              <i class="iconfont icon_shanchu" @click="deletePreset1($event, 'preset3')"></i>
            </li>
            <li @click="preset($event)">
              <span @dblclick="editName1($event)" class="valShow">{{preset4}}</span>
              <!--              <span class="valShow">{{preset1}}</span>-->
              <i class="iconfont icon_jiasu1"></i>
              <div class="presetInput">
                <el-input :clearable="true" :autofocus="true"  v-model="preset4" placeholder="添加新预置点" @blur="confirm1"></el-input>
              </div>
              <i class="iconfont icon_shanchu" @click="deletePreset1($event, 'preset4')"></i>
            </li>
            <li @click="preset($event)">
              <span @dblclick="editName1($event)" class="valShow">{{preset5}}</span>
              <!--              <span class="valShow">{{preset1}}</span>-->
              <i class="iconfont icon_jiasu1"></i>
              <div class="presetInput">
                <el-input :clearable="true" :autofocus="true"  v-model="preset5" placeholder="添加新预置点" @blur="confirm1"></el-input>
              </div>
              <i class="iconfont icon_shanchu" @click="deletePreset1($event, 'preset5')"></i>
            </li>
            <li @click="preset($event)">
              <span @dblclick="editName1($event)" class="valShow">{{preset6}}</span>
              <!--              <span class="valShow">{{preset1}}</span>-->
              <i class="iconfont icon_jiasu1"></i>
              <div class="presetInput">
                <el-input :clearable="true" :autofocus="true"  v-model="preset6" placeholder="添加新预置点" @blur="confirm1"></el-input>
              </div>
              <i class="iconfont icon_shanchu" @click="deletePreset1($event, 'preset6')"></i>
            </li>
          </ul>
        </div>
      </div>
    </div>
    <div class="nameFramk">
      <span class="titleName">{{titleName}}</span>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
    import $ from 'jquery'
    import './adapter.js'
    import './platform.js'
    import {H5sPlayerWS,H5sPlayerHls,H5sPlayerRTC} from './h5splayer.js'
    import {H5siOS, H5sPlayerCreate, H5sSafariBrowser, GetURLParameter,} from './h5splayerhelper.js'
    export default {
        name: "videoPlayer",
        props: ['h5id', 'h5videoid','videoIndex'],
        data () {
          return {
              // 预置点值
              preset1: '',
              preset2: '',
              preset3: '',
              preset4: '',
              preset5: '',
              preset6: '',
              videoId: this.h5videoid,
              checkItem: '',
              h5handler: undefined,
              playControls: true,
              cloudControls: false,
              controlName: '云台控制',
              presetNum: 0,
              timeCount: false,
              recordIcon: 'icon_luxiang1',
              screenIcon: 'iconfont icon_quanping1',
              titleName: '',
              h: '00',
              m: '00',
              s: '00',
              hour: 0,
              minute: 0,
              second: 0,
              timer: '',
              recordStyle: {},
              cStream: 'sub',
              cProto: 'RTC',
              protoIcon: 'iconfont icon_RTC',
              streamIcon: 'iconfont icon_zimaliu'
          }
        },
        beforeDestroy () {
            if (this.h5handler != undefined) {
                this.h5handler.disconnect()
                delete this.h5handler
                this.h5handler = undefined
            }
        },
        mounted () {
            let that = this;

            // 视频在线播放
             try{this.$root.bus.$off('videoPlay1');} catch(e){}
            this.$root.bus.$on('videoPlay1', function (data, videoId, proto, stream, hId) {
                that.videoPlay1(data, videoId, proto, stream, hId);
            });

            // 接收关闭所有视频的信号
            try{ this.$root.bus.$off('closeAllVideo1');} catch(e){}
            this.$root.bus.$on('closeAllVideo1', function (n) {
                if (that.h5handler !== undefined) {
                    that.h5handler.disconnect()
                    delete that.h5handler
                    that.h5handler = undefined
                    if(n != 2)
                    that.$Notice.info({
                        title: '关闭成功'
                    })
                }
            });
        },
        methods: {

            editName1 (e) {
                let aimDom = $(e.target);
                aimDom.css({
                    display: 'none'
                })
                aimDom.next().next().css({
                    display: 'inline-block'
                })
            },

            confirm1 (e) {
                let aimDom = $(e.target);
                aimDom.parents('.presetInput').css({
                    display: 'none'
                })
                aimDom.parents('.presetInput').prev().prev().css({
                    display: 'inline-block'
                })
            },

            // 改变码流
            changeStream1 (e) {
                e.stopPropagation();
                if (this.streamIcon === 'iconfont icon_zhumaliu') {
                    this.streamIcon = 'iconfont icon_zimaliu';
                    this.cStream = 'sub';
                    this.videoPlay1(this.checkItem, this.h5videoid, this.cProto, this.cStream, this.h5id);
                    this.$Notice.info({
                        title: '已切换为子码流'
                    })
                } else {
                    this.streamIcon = 'iconfont icon_zhumaliu';
                    this.cStream = 'main';
                    this.videoPlay1(this.checkItem, this.h5videoid, this.cProto, this.cStream, this.h5id);
                    this.$Notice.info({
                        title: '已切换为主码流'
                    })
                }
            },

            // 视频区域全屏显示
            FullScreen1 (event, other) {
                if (this.screenIcon === 'iconfont icon_quanping1') {
                    this.screenIcon = 'iconfont icon_quxiaoquanping';
                } else {
                    this.screenIcon = 'iconfont icon_quanping1'
                }

                let aimDom = '';
                let elem = '';
                aimDom = '#' + this.h5id;
                elem = $(aimDom).get(0)
                if (
                    document.fullscreenEnabled ||
                    document.webkitFullscreenEnabled ||
                    document.mozFullScreenEnabled ||
                    document.msFullscreenEnabled
                ) {
                    if (
                        document.fullscreenElement ||
                        document.webkitFullscreenElement ||
                        document.mozFullScreenElement ||
                        document.msFullscreenElement
                    ) {
                        if (document.exitFullscreen) {
                            document.exitFullscreen()
                        } else if (document.webkitExitFullscreen) {
                            document.webkitExitFullscreen()
                        } else if (document.mozCancelFullScreen) {
                            document.mozCancelFullScreen()
                        } else if (document.msExitFullscreen) {
                            document.msExitFullscreen()
                        }

                        this.updateUIExitFullScreen()
                    } else {

                        if (elem.requestFullscreen) {
                            elem.requestFullscreen()
                        } else if (elem.webkitRequestFullscreen) {
                            elem.webkitRequestFullscreen()
                        } else if (elem.mozRequestFullScreen) {
                            elem.mozRequestFullScreen()
                        } else if (elem.msRequestFullscreen) {
                            elem.msRequestFullscreen()
                        }
                    }
                } else {
                    console.log('Fullscreen is not supported on your browser.')
                }
            },

            // 改变协议
            changeProto1 (e) {
                e.stopPropagation();
                // if (this.h5handler === undefined) {
                //     this.$Notice.info({
                //         title: '请选择设备'
                //     })
                //     return
                // }
                if (this.protoIcon === 'iconfont icon_RTC') {
                    this.protoIcon = 'iconfont icon_WS';
                    this.cProto = 'WS';
                    this.videoPlay1(this.checkItem, this.h5videoid, this.cProto, this.cStream, this.h5id);
                    this.$Notice.info({
                        title: '已切换为WS协议'
                    })
                } else {
                    this.protoIcon = 'iconfont icon_RTC';
                    this.cProto = 'RTC';
                    this.videoPlay1(this.checkItem, this.h5videoid, this.cProto, this.cStream, this.h5id);
                    this.$Notice.info({
                        title: '已切换为RTC协议'
                    })
                }
            },

            // 控制录像
            recordControl1 (e) {
                e.stopPropagation();
                let that = this;
                if (this.recordIcon === 'icon_luxiang1') {
                    this.recordIcon = 'icon_luxiangzhong';
                    this.timeCount = true;
                    this.videoRecord('start');
                    // aimDom.css('background', '#1F232F');
                    this.recordStyle = {
                        background: '#1F232F'
                    };
                    // 录像计时器
                    if (this.timer === '') {
                        this.timer = setInterval(function () {
                            if (that.recordIcon === 'icon_luxiangzhong') {
                                that.recordIcon = '';
                            } else {
                                that.recordIcon = 'icon_luxiangzhong';
                            }
                            that.second++;
                            if (that.second === 60) {
                                that.minute++;
                                that.second = 0;
                            }
                            if (that.minute === 60) {
                                that.hour++;
                                that.minute = 0;
                            }
                            that.s = that.second < 10 ? '0' + that.second : that.second;
                            that.m = that.minute < 10 ? '0' + that.minute : that.minute;
                            that.h = that.hour < 10 ? '0' + that.hour : that.hour;
                        }, 1000);
                    }
                } else {
                    this.h = '00';
                    this.m = '00';
                    this.s = '00';
                    this.hour = 0;
                    this.minute = 0;
                    this.second = 0;
                    clearInterval(this.timer);
                    this.timer = '';

                    this.recordIcon = 'icon_luxiang1';
                    this.videoRecord('end');
                    this.recordStyle = {
                        background: 'rgba(31, 35, 47, 0.5)'
                    };
                    // aimDom.css('background', 'rgba(31, 35, 47, 0.5)')
                    this.timeCount = false;
                }
            },

            // 删除预置点
            deletePreset1 (e, aim) {
                this[aim] = '';
                e.stopPropagation();
                this.presetNum--;
                let aimDom = $(e.target);
                aimDom.prev().children().val('');
                aimDom.prev().css('display', 'none');
                aimDom.css('display', 'none');
                aimDom.prev().prev().css('display', 'inline-block');
                aimDom.prev().prev().prev().css('display', 'none');
            },

            // 预置点区高亮
            preset (e) {
                e.stopPropagation();
                let aimDom = $(e.target);
                let localName = aimDom[0].localName;
                let className = aimDom[0].className;
                if (localName !== 'li' && localName !== 'div' && localName !== 'input' && localName !== 'span') {
                  if (className === 'iconfont icon_jiasu1') {
                      this.presetNum++;
                  }
                      aimDom.css('display', 'none');
                      aimDom.next().css('display', 'inline-block');
                      aimDom.next().next().css('display', 'inline-block');
                      aimDom = aimDom.parents('li');
                }
                if (!aimDom.hasClass('presetLight') && localName !== 'div') {
                    if (localName === 'span') {
                        aimDom = aimDom.parents('li');
                    }
                    $('.dotList li[class*="presetLight"]').removeClass('presetLight');
                    aimDom.addClass('presetLight');
                }
            },

            // 改变控制方式
            changeControls1 (e) {
                e.stopPropagation();
                if (this.cloudControls === false) {
                    this.playControls = false;
                    this.cloudControls = true;
                    this.controlName = '播放控制';
                } else {
                    this.playControls = true;
                    this.cloudControls = false;
                    this.controlName = '云台控制';
                }
            },

            // 改变当前播放窗口的缩放比例
            changeZoom (val) {
                this.$nextTick(function () {
                    $('.container').css({
                        zoom: val
                    });
                })
            },

            // 停止视频播放
            videoClose1 (id, e) {
                e.stopPropagation();
                  if (this.h5handler != undefined) {
                      this.h5handler.disconnect()
                      delete this.h5handler
                      this.h5handler = undefined
                      this.$Notice.info({
                          title: '关闭成功'
                      })

                      $('#' + id).get(0).load();
                      $('#' + id).get(0).poster = '';

                      this.cutUsingEq1(this.titleName);
                      let titleDom = '#' + this.h5id + ' ' + '.titleName';
                      this.titleName = '';
                      $(titleDom).css({
                          display: 'none'
                      })
                  }
            },

            // 视频在线预览
            videoPlay1 (item, videoId, proto, stream, hId) {
            //     if (this.h5handler != undefined) {
            //         this.cutUsingEq1(this.titleName);
            //         this.h5handler.disconnect()
            //         delete this.h5handler
            //         this.h5handler = undefined
            //     }
            //     let aimDom = '#' + videoId;
            //    if (H5siOS() === true || H5sSafariBrowser() === true) {
            //         $(aimDom).prop("controls", true);
            //     }

            //     var strToken;
            //     strToken = GetURLParameter("token");
            //     if (strToken === undefined) {
            //         strToken = 'token1';
            //     }
            //     var strStream = stream;
                let targetName = item.Path.split('%');
                this.titleName = targetName[0] + ' - ' + targetName[1];
                $("#"+videoId).parent().find(".titleName").html(this.titleName).css({ display: 'inline-block'});

                var conf1 = {
                    videoid: videoId,
                    protocol: "http:",
                    host: "139.9.204.98:8080",
                    rootpath: "/",
                    token: item.token,
                    streamprofile: "main",
                    hlsver: "v1",
                    session: "e90a6c85-5499-4f31-a937-a1a974bbe0a4"
                };
                console.log('视频在线预览传参---',conf1);
                // 选择WS或RTC协议

                if (proto == 'RTC' || (H5siOS() === true)) {

                    this.h5handler = new H5sPlayerRTC(conf1)
                } else {

                    this.h5handler = new H5sPlayerWS(conf1)
                }

                this.h5handler.connect();
                // $(aimDom).get(0).onplay = function() {
                //     console.log("The video has started to play");
                // };
            },

            // 除去正在使用的监控视频
            cutUsingEq1 (eqName) {
                let set = this.$store.state.usingEq;
                for (let i in set) {
                    if (set[i] === eqName) {
                        set.splice(i, 1);
                    }
                }
                this.$store.state.usingEq = set;
            },

            // 判断字符串是否为空
            isNull (str) {
                return str === null || str.length === 0 || str === '';
            },

            // 视频云台控制
            videoOperation1 (direct, e) {
                e.stopPropagation();
                // if (this.isNull(this.checkItem)) {
                //     this.$Notice.info({
                //         title: "请选择设备"
                //     });
                //     return false;
                // }
               this.$api.canVideoOperator({
                    hostUrl: "/api/v1/Ptz",
                    session: window.localStorage.ac_session,
                    token: this.checkItem.token,
                    action: direct,
                    speed: 1,
                    preset: "",
               }).then(res => {
                    res = res.data;
                    if (res.HttpStatus == 200) {
                        var result = res.HttpData;
                        if (result.code == 200) {
                            var data = result.data;
                        }
                    }
                }).catch(err => {
                    console.log('云台控制失败！')
                });
            },

            // 快照
            videoSnapShot (e) {
                e.stopPropagation();
                // if (this.h5handler === undefined) {
                //     this.$Notice.info({
                //         title: '请选择设备'
                //     })
                //     return
                // }
               this.$api.getVideoSnapshot({
                    hostUrl: "/api/v1/Snapshot",
                    session: window.localStorage.ac_session,
                    token: this.checkItem.token,
               }).then(res => {
                      res = res.data;
                      let code =  res.HttpData.code;
                      if (code === 200) {
                              this.$Notice.info({
                                  title: '快照成功！',
                                  type: 'success'
                              })
                      }
                }).catch(err => {
                    console.log('快照失败！')
                });
            },

            // 录像
            videoRecord (type) {
                let apiName = '';
                if (type === 'start') {
                    apiName = '/api/v1/ManualRecordStart';
                } else {
                    apiName = '/api/v1/ManualRecordStop';
                }
               this.$api.getVideoSnapshot({
                    hostUrl: apiName,
                    session: window.localStorage.ac_session,
                    token: this.checkItem.token,
               }).then(res => {
                    res = res.data;
                    let code =  res.HttpData.code;
                    if (code === 200) {
                        if (type === 'start') {
                            this.$Notice.info({
                                title: '已开始录像'
                            })
                        } else {
                            this.$Notice.info({
                                title: '已停止录像'
                            })
                        }
                    }
                }).catch(err => {
                    console.log('录像失败')
                });
            }
        }
    }
</script>

 <style lang="scss" src="@assets/styles/videoPlayer.scss" scoped></style>
